import datetime
import sys
from xtquant.xttrader import XtQuantTraderCallback


class MyXtQuantTraderCallback(XtQuantTraderCallback):
    def on_disconnected(self):
        """
        连接状态回调
        :return:
        """
        print(datetime.datetime.now(), "连接断开connection lost")
        global xt_trader
        xt_trader = None

    def on_account_status(self, status):
        """
        账号状态信息推送
        :param response: XtAccountStatus对象
        :return:
        """
        print("账号状态信息推送on_account_status")
        print(status.account_id, status.account_type, status.status)
        print(datetime.datetime.now(), sys._getframe().f_code.co_name)

    def on_stock_asset(self, asset):
        """
        资金变动推送
        :param asset: XtAsset对象
        :return:
        """
        print("资金变动推送on asset callback")
        print(asset.account_id, asset.cash, asset.total_asset)

    def on_stock_order(self, order):
        """
        委托回报推送
        :param order: XtOrder对象
        :return:
        """
        print(datetime.datetime.now(), '委托回调', order.order_remark)
        print(order.stock_code, order.order_status, order.order_sysid)

    def on_stock_trade(self, trade):
        """
        成交变动推送
        :param trade: XtTrade对象
        :return:
        """
        print(datetime.datetime.now(), '成交回调', trade.order_remark)
        print(trade.account_id, trade.stock_code, trade.order_id)

    def on_stock_position(self, position):
        """
        持仓变动推送
        :param position: XtPosition对象
        :return:
        """
        print("on position callback")
        print(position.stock_code, position.volume)

    def on_order_error(self, order_error):
        """
        委托失败推送
        :param order_error: XtOrderError 对象
        :return:
        """
        print("委托失败单号【", order_error.order_id, "】\n", "失败错误码:", order_error.error_id, "\n", "失败具体说明:",
              order_error.error_msg)

    def on_cancel_error(self, cancel_error):
        """
        撤单失败信息推送
        :param cancel_error: XtCancelError 对象
        :return:
        """
        print("on cancel_error callback")
        print(cancel_error.order_id, cancel_error.error_id, cancel_error.error_msg)

    def on_order_stock_async_response(self, response):
        """
        异步下单回报推送
        :param response: XtOrderResponse 对象
        :return:
        """
        print(f"异步委托回调 {response.order_remark}")
        print(response.account_id, response.order_id, response.seq)

    def on_cancel_order_stock_async_response(self, response):
        """
        :param response: XtCancelOrderResponse 对象
        :return:
        """
        print(datetime.datetime.now(), sys._getframe().f_code.co_name)
        print(response.account_id, response.order_id, response.seq)
